<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-4-3
 */

namespace weapp\MonkWeixin\logic;

use think\Db;
use weapp\MonkWeixin\model\MonkWeixinModel;
/**
 * 业务逻辑
 */
class MonkWeixinLogic
{
    private $model;
    private $weappData;
    /**
     * 析构函数
     */
    function  __construct() {
        $this->model = new MonkWeixinModel;  
        $this->weappData = $this->model->weappData();
    }
    function insertAction($type){
        switch ($type) {
            case 'function':                
                $filePath = "extend/function.php"; // 文件路径                
                if (file_exists($filePath)) {            
                    $fileContent = @file_get_contents(realpath($filePath));
                    $check = stristr($fileContent, 'diy_monkWechatYx');
                    if (!$check) {
                       $str =<<<EOF

if (!function_exists('diy_monkWechatYx')) {
        //微信营销客服     
    function diy_monkWechatYx(&\$post = []) {
        if (class_exists("weapp\MonkWeixin\logic\MonkWeixinLogic")) {
            \$logic = new \weapp\MonkWeixin\logic\MonkWeixinLogic;
            \$logic->monkWechatYx(\$post);
        }
    }
}
EOF;
                    $fileContent .= $str;
                    @file_put_contents(realpath("extend/function.php"), $fileContent);
                    }                    
                } else {
                    @copy(realpath("weapp/MonkWeixin/extend/function.php"), realpath("extend/function.php"));
                }
                break;
                case 'view':                
                    $content = '';
                    if (file_exists("application/home/controller/View.php")) {
                        $content = @file_get_contents(realpath("application/home/controller/View.php"));
                    }                     
                    if (!empty($content) && !stristr($content, 'diy_monkWechatYx')) {      

                                $replace =<<<EOF
            //微信营销客服 
        if (function_exists('diy_monkWechatYx')) {
            diy_monkWechatYx(\$this->eyou);
        }
        \$this->assign('eyou', \$this->eyou);
EOF;
                        $content = str_replace("\$this->assign('eyou', \$this->eyou);", $replace, $content);                                                                                   
                        @file_put_contents(realpath("application/home/controller/View.php"), $content);   
                    }                                            
                break;            
            default:
                // code...
                break;
        }
    }
    //微信营销
    public function monkWechatYx(&$post = [])
    {                           
        if ($this->isSpider() !== false) {            
            return;
        }        
        $row = $this->weappData;        
        // 检查功能是否开启                 
        if (empty($row['data']['is_open']) || $row['data']['is_open'] != 1) {
            return;
        }        
        // 根据条件处理内容
        if (empty($row['data']['is_news_type']) && !in_array($post['field']['typeid'], $row['data']['is_typeids'])) {                        
            $post['field']['content'] = self::_todo($post, $row);
        } elseif (!empty($row['data']['is_news_type'])) {
            $ids = explode(',', $row['data']['ids']);
            if (in_array($post['field']['aid'], $ids)) {
                $post['field']['content'] = self::_todo($post, $row);
            }
        }        
        return $post['field']['content'];           
    }
    public function _todo($post = [], $row = [])
    {                
        if ($row['data']['is_news'] == 3) {
            return $post['field']['content'];
        }                
        if ($row['data']['is_news'] == 1 && !isMobile()) {
            return $post['field']['content'];
        }                
        return self::_newDuan(
            $row['data']['is_duan'],
            $row['data']['is_news_wz'],
            $post['field']['content'],
            $row
        );
    }
    /**
     *   段落内容
     * @Author    Wolf
     * @DateTime  2025-02-06
     */
    public function _newDuan($duan='',$wz='',$content,$row=[]){
        if(empty($duan)){            
            switch ($wz) {
                case 0:
                    // 文章开头
                    $content = self::_yxhtm().$content;
                    break;
                case 1:
                    // 第一段落之后                    
                    $content_arr = self::parCount($content);
                    if (!empty($content_arr)) {
                        $count = count($content_arr);
                        if ($count <= 1) {
                            $content = $content.self::_yxhtm();
                        } else {
                            $content = self::str_replace($content_arr[0], $content_arr[0].self::_yxhtm(), $content);
                        }
                    }
                    break;
                case 2:
                    // 文章中间
                    $content_arr = self::parCount($content);
                    if (!empty($content_arr)) {
                        $count = count($content_arr);
                        $idx = intval($count / 2);
                        $content = self::str_replace($content_arr[$idx], self::_yxhtm().$content_arr[$idx], $content);
                    }
                    break;                
                default:
                    // 文章尾部
                    $content = $content.self::_yxhtm();
                    break;
            } 
        }else{
            $content_arr = self::parCount($content);
            if (!empty($content_arr)) {                
                $content = self::str_replace($content_arr[$duan], $content_arr[$duan].self::_yxhtm(), $content);                
            }
        }             
        return $content;
    }
    /**
     * 计算内容段落
     */
    private function parCount($content)
    {
        $arr = [];
        $section =['div','p'];
        if (empty($section) || empty($content)) {
            $arr = [$content];
        } else {
            $patterns = [];
            foreach ($section as $key => $value) {
                $patterns[] = "(<{$value}([^\>]*)>(?:(?!<\/{$value}>)[\s\S])*<\/{$value}>)";
            }
            $pattern = implode('|', $patterns);
            preg_match_all('/('.$pattern.')/i', $content, $matches);
            if (!empty($matches[0])) {
                $arr = $matches[0];
            }
        }
        return $arr;
    }
    /**
     * 字符串替换    
     */
    private function str_replace($needle, $replace, $str)
    {
        $pos = strpos($str, $needle);
        if ($pos === false) {
            return $str;
        }
        return substr_replace($str, $replace, $pos, strlen($needle));
    }
    /**
     *  插入文中内容
     * @Author    Wolf
     * @DateTime  2025-02-06
     * @copyright [copyright]
     * @license   [license]
     * @version   [version]
     * @return    [type]      [description]
     */
    private function _yxhtm(){
        $row = $this->weappData['data']; 
        if(isset($row['btn_color']) && $row['btn_color']){
            $is_style = 'background: '.$row['btn_color'].";";
        }else{
            $is_style='';
        }

        $randomKey = array_rand($row['proimg']);                    
        $randomItem = $row['proimg'][$randomKey];        

        $row['wx_intro'] =  $randomItem['wechat_name'];      
        $row['code_intro'] =  $randomItem['code_img'];  
        $htm='<div class="monk-weixin-insert"  style="display:none">
    <img src="'.$row['code_intro'] .'" class="monkshow qrcode-ez"><span class="monk-wx-user">
        微信号：<em>'.$row['wx_intro'].'</em></span><br><span class="monk-wx-tip">'.$row['ad_intro'].'</span><br><span class="monk-wx-btn monk-wx-show" style="'.$is_style.'" data-clipboard-text="'.$row['wx_intro'].'"><i class="iconfont monk-wx-icon-weixin"></i>复制微信号</span></div>';
        return $htm;
    }
    /**
     *  判断是否是爬虫
     * @Author    Wolf
     * @DateTime  2025-02-06
     * @copyright [copyright]
     * @license   [license]
     * @version   [version]
     * @return    boolean     [description]
     */
    public function isSpider()
    {
        $spiderList = [
            'BaiduSpider',
            'Googlebot',
            '360Spider',
            'Sogou web spider',
            // 可以继续添加其他蜘蛛的User - Agent标识
        ];
        $userAgent = isset($_SERVER['HTTP_USER_AGENT'])? $_SERVER['HTTP_USER_AGENT'] : '';
        foreach ($spiderList as $spider) {
            if (stripos($userAgent, $spider)!== false) {
                return true;
            }
        }
        return false;
    }
}
